//引入 vue
import Vue from "vue";
//引入 store
import store from "@/store";
//引入报错的全局方法
import {Message, Loading} from "element-ui";

console.log(process.env.VUE_APP_API_URL)
//1.引入axios
import axios from "axios";

const service = axios.create({
    baseURL: process.env.VUE_APP_API_URL,//"http://localhost:3007",
    timeout: 10000})

//创建 保存 旋转小图标的变量
var loadObj = null;

//请求拦截
service.interceptors.request.use(
    (config) => {
        console.log(config);
        if (!loadObj) {
            loadObj = Loading.service({
                lock: true,
                target: "#loading",
                text: "加载中...",
                spinner: "el-icon-loading",
                background: "rgba(0,0,0,0.5)"
            })
        }
        //假设有token ，需要设置 token 令牌
        config.headers['user-token'] = store.getters.token;
        return config;
    },
    (error) => {
        Vue.nextTick(() => {// 以服务的方式调用的 Loading 需要异步关闭
            loadObj.close();
        });
        return Promise.reject(error);

    }
);


service.interceptors.request.use(
    (response) => {
        console.log(response);
        return response;
    }, (error) => {
        return Promise.reject(error);
    }
);

//响应拦截
service.interceptors.response.use(
    (response) => {
        console.log(35, response);
        // setTimeout(() => {
            Vue.nextTick(() => {
                loadObj.close();
            });
        // }, 2000);
        if (response.data.code == 666) {
            return response;
        } else {
            Message({
                message: response.data.msg,
                type: "error"
            });
            return Promise.reject(response.data.msg);
        }
    }, (error) => {
        Vue.nextTick(() => {
            loadObj.close();
        });
        Message({
            message: error,
            type: "error"
        });
        return Promise.reject(error);
    }
);

export default service;